package sandau.self_improvement_wall.security;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author LuanZheng
 * @date 2025/5/14 11:48
 */
@Service
public class RateLimiter {
    private final RedisTemplate<String, String> redisTemplate;
    private static final String RATE_LIMIT_KEY_PREFIX = "rate_limit:ip:";
    private static final int LIMIT = 1000; // 每分钟1000次
    private static final long EXPIRE = 60; // 60秒

    public RateLimiter(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean allowRequest(String ip) {
        String key = RATE_LIMIT_KEY_PREFIX + ip;
        long current = redisTemplate.opsForValue().increment(key);
        if (current == 1) {
            redisTemplate.expire(key, EXPIRE, TimeUnit.SECONDS);
        }
        return current <= LIMIT;
    }
}